package week_07;


import java.util.Iterator;

/**
 * @author HP
 */
public class Queue<T> implements Iterable{
    private Node head;
    /**
     * 定义最后一个节点
     */
    private Node last;
    private int N;



    private class Node {
        public T item;
        public Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    public Queue() {
        this.head = new Node(null, null);
        this.last = null;
        this.N = 0;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    public int size() {
        return N;
    }

    public Object get(int i) {
        Node n = head.next;
        for (int index = 0; index < i; index++) {
            n = n.next;
        }
        return n.item;
    }

    public void push(T t) {
        if (last == null) {
            last = new Node(t, null);
            head.next = last;
        } else {
            Node oldLast = last;
            last = new Node(t, null);
            oldLast.next = last;
        }
        N++;
    }

    public T pop() {
        if (isEmpty()) {
            return null;
        }
        Node oldFirst = head.next;
        head.next = oldFirst.next;
        N--;
        if (isEmpty()){
            last=null;
        }
        return oldFirst.item;

    }

    public void fullArrangement(String str){
        push((T) String.valueOf(str.charAt(0)));
        StringBuilder s = new StringBuilder(str);
        for (int i = 0; i < str.length()-1; i++) {
            int size= N;
            for (int j=0;j< size;j++){
                String pop = (String) pop();
                String cur = s.substring(i+1,i+2);
                for (int index = 0; index < i+2; index++) {
                    StringBuilder sb = new StringBuilder(cur);
                    StringBuilder out = new StringBuilder(pop);
                    out.insert(index,sb);
                    push((T) String.valueOf(out));
                }
            }

        }

    }

    @Override
    public Iterator<T> iterator() {
        return new QIterator();
    }
    private class QIterator implements  Iterator{
        private Node n;

        public QIterator() {
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n=n.next;
            return n.item;
        }
    }
}
